"use client";

import { z } from "zod";
import MarkdownEditor from "@/components/markdown-editor";
import { CONTENT_ZOD, PERSONAL_ZOD, TITLE_ZOD } from "@/shared/restrictions/post";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormField } from "@/components/ui/form";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";

const formSchema = z.object({
  content: CONTENT_ZOD,
  title: TITLE_ZOD,
  personal: PERSONAL_ZOD,
});

export type PostEditorFormValues = z.infer<typeof formSchema>;

type Props = {
  initValues: PostEditorFormValues;
  onSave: (values: PostEditorFormValues) => void;
};

export default function PostEditorForm({ initValues, onSave }: Props) {
  const form = useForm<PostEditorFormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      content: initValues.content,
      title: initValues.title,
      personal: initValues.personal,
    },
  });

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSave)} className="p-2">
        <div className="flex border border-zinc-200">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => <input className="flex-1 p-2 mr-2" placeholder="Title" {...field} />}
          />
          <FormField
            control={form.control}
            name="personal"
            render={({ field }) => (
              <span className="flex items-center mr-2">
                <Checkbox className="mr-1" checked={field.value} onCheckedChange={field.onChange} />
                Personal
              </span>
            )}
          />
          <Button type="submit">Save</Button>
        </div>

        <FormField
          control={form.control}
          name="content"
          render={({ field }) => (
            <MarkdownEditor
              value={field.value}
              onChange={field.onChange}
              placeholder="Markdown here."
              heightMinus="140px"
              className="border border-zinc-200 border-t-0"
            />
          )}
        />
      </form>
    </Form>
  );
}
